package com.zbkj.business.core;

import com.tiangong.framework.bo.CDO;
import com.tiangong.framework.util.SnowFlakeGenerateIdWorker;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.Buffer;
import java.nio.charset.Charset;
import java.text.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 依赖包
 * commons-codec:commons-codec:1.6
 */

@Slf4j
public class Utils  {
    // 默认除法运算精度
    private static final Integer DEF_DIV_SCALE = 2;

    /**
     * 获取雪花算法ID
     *
     * @param workerId：工作ID       0-63
     * @param datacenterId：数据中心ID 0-15
     * @return
     */
    public static long getSnowFlakeGenerateId(int workerId, int datacenterId) {
        long flowNoNew = new SnowFlakeGenerateIdWorker(workerId, datacenterId).nextId();
        return flowNoNew;
    }

    /**
     * 提供精确的加法运算。
     *
     * @param value1 被加数
     * @param value2 加数
     * @return 两个参数的和
     */
    public static Double add(Double value1, Double value2) {
        BigDecimal b1 = new BigDecimal(Double.toString(value1));
        BigDecimal b2 = new BigDecimal(Double.toString(value2));
        return b1.add(b2).doubleValue();
    }

    public static Double add(Object ... value) {
        Double d=0.0;
        for (Object a : value) {
            BigDecimal b1 = new BigDecimal(Double.toString(d));
            BigDecimal b2 = new BigDecimal(a.toString());
            d=b1.add(b2).doubleValue();
        }
        return d;
    }

    /**
     * 提供精确的除法
     *
     * @param dividend
     * @param divisor
     * @param scale
     * @return
     */
    public static Double divide(Object dividend, Object divisor, Integer scale) {
        if (scale < 0) {
            throw new IllegalArgumentException("The scale must be a positive integer or zero");
        }
        BigDecimal b1 = new BigDecimal(dividend.toString());
        BigDecimal b2 = new BigDecimal(divisor.toString());
        return b1.divide(b2, scale, BigDecimal.ROUND_UP).doubleValue();
    }

    /**
     * 提供精确的减法运算。
     *
     * @param value1 被减数
     * @param value2 减数
     * @return 两个参数的差
     */
    public static double sub(Double value1, Double value2) {
        BigDecimal b1 = new BigDecimal(Double.toString(value1));
        BigDecimal b2 = new BigDecimal(Double.toString(value2));
        return b1.subtract(b2).doubleValue();
    }

    /**
     * 提供精确的乘法运算。
     *
     * @param value1 被乘数
     * @param value2 乘数
     * @return 两个参数的积
     */
    public static Double multiply(Double value1, Double value2) {
        BigDecimal b1 = new BigDecimal(Double.toString(value1));
        BigDecimal b2 = new BigDecimal(Double.toString(value2));
        return b1.multiply(b2).doubleValue();
    }

    public static Double multiply(Object value1, Object value2) {
        BigDecimal b1 = new BigDecimal(value1.toString());
        BigDecimal b2 = new BigDecimal(value2.toString());
        return b1.multiply(b2).doubleValue();
    }
    public static Double multiply(Object ... value) {
        Double d=1.0;
        for (Object a : value) {
            BigDecimal b1 = new BigDecimal(Double.toString(d));
            BigDecimal b2 = new BigDecimal(a.toString());
            d=b1.multiply(b2).doubleValue();
        }
        return d;
    }

//    public static double multiply(Object value1, Object value2, int n) {
//        BigDecimal b1 = new BigDecimal(value1.toString());
//        BigDecimal b2 = new BigDecimal(value2.toString());
//        double d = b1.multiply(b2).doubleValue();
//
//        double format = 1.0;
//        switch (n) {
//            case 0:
//                format = 1;
//                break;
//            case 1:
//                format = 10.0;
//                break;
//            case 2:
//                format = 100.0;
//                break;
//            case 3:
//                format = 1000.0;
//                break;
//            case 4:
//                format = 10000.0;
//                break;
//            case 5:
//                format = 100000.0;
//                break;
//        }
//        return ((int) (d * format)) / format;
//    }

    public static double multiply(Object value1, Object value2, int n) {
        BigDecimal b1 = new BigDecimal(value1.toString());
        BigDecimal b2 = new BigDecimal(value2.toString());
        double d = b1.multiply(b2).doubleValue();
        String format = new StringBuffer("%.").append(n).append("f").toString();
        return Double.parseDouble(String.format(format, d));
    }

    /**
     * 57      * 提供（相对）精确的除法运算，当发生除不尽的情况时， 精确到小数点以后10位，以后的数字四舍五入。
     * 58      *
     * 59      * @param dividend 被除数
     * 60      * @param divisor  除数
     * 61      * @return 两个参数的商
     * 62
     */
    public static Double divide(Double dividend, Double divisor) {
        return divide(dividend, divisor, DEF_DIV_SCALE);
    }

    /**
     * 68      * 提供（相对）精确的除法运算。 当发生除不尽的情况时，由scale参数指定精度，以后的数字四舍五入。
     * 69      *
     * 70      * @param dividend 被除数
     * 71      * @param divisor  除数
     * 72      * @param scale    表示表示需要精确到小数点以后几位。
     * 73      * @return 两个参数的商
     * 74
     */
    public static Double divide(Double dividend, Double divisor, Integer scale) {
        if(divisor==0){
            return 0.0;
        }
        if (scale < 0) {
            throw new IllegalArgumentException("The scale must be a positive integer or zero");
        }
        BigDecimal b1 = new BigDecimal(Double.toString(dividend));
        BigDecimal b2 = new BigDecimal(Double.toString(divisor));
        return b1.divide(b2, scale, BigDecimal.ROUND_UP).doubleValue();
    }


    /**
     * 提供指定数值的（精确）小数位四舍五入处理。
     * 86      *
     * 87      * @param value 需要四舍五入的数字
     * 88      * @param scale 小数点后保留几位
     * 89      * @return 四舍五入后的结果
     * 90
     */
    public static double round(double value, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException("The scale must be a positive integer or zero");
        }
        BigDecimal b = new BigDecimal(Double.toString(value));
        BigDecimal one = new BigDecimal("1");
        return b.divide(one, scale, RoundingMode.HALF_UP).doubleValue();
    }

    public static String parseSQL(CDO cdoData, String strSQLText) {
        Pattern pattern = Pattern.compile("(\\{[A-Za-z0-9._]*\\})");
        Matcher matcher = pattern.matcher(strSQLText);
        List<String> strSQLItemList = new ArrayList<String>();
        while (matcher.find()) {
            strSQLItemList.add(matcher.group());
        }
        for (int i = 0; i < strSQLItemList.size(); i++) {
            String strFieldItem = strSQLItemList.get(i).replaceAll("\\{|\\}", "");
//           System.out.println(strFieldItem);
            if (cdoData.containsKey(strFieldItem)) {
                strSQLText = strSQLText.replace(strSQLItemList.get(i), cdoData.getString(strFieldItem));
            } else {
                log.info(strFieldItem + "不存在");
            }
        }
//        System.out.println(strSQLText);
        return strSQLText;
    }

    public static long getFenFromYun(double value) {
        return Double.valueOf(multiply(100, value)).longValue();
    }

    /**
     * 将Long类型的金额：分转换为Double类型的：元，保留两位小数
     *
     * @param value
     * @return
     */
    public static Double getYuanFromFen(Long value) {
        boolean negative = false;
        if (value < 0) {
            negative = true;
            value = Math.abs(value);
        }
        String yuan = value / 100 + "." + value % 100 / 10 + value % 100 % 10;
        if (negative) {
            return 0 - Double.valueOf(yuan);
        }
        return Double.valueOf(yuan);
    }



    public static String getBarcodeOfWeigthGoods(String inputBarcode, int predixCutLength) {
        String barcode = inputBarcode;
        if (inputBarcode.length() == 13) {
            barcode = inputBarcode.substring(predixCutLength, 7);
        }
        return barcode;
    }

    /**
     * 提供日期格式的比较：被比较时间与当前时间相差天数。
     *
     * @param date1 被比较时间
     * @return 两个参数的积
     */
    public static Long betweenDays(String date1) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        long betweenDate = 0;
        Long nowDate = calendar.getTime().getTime();//获得毫秒型日期
        try {
            Long specialDate = sdf.parse(date1).getTime();
            betweenDate = (specialDate - nowDate) / (1000 * 60 * 60 * 24); //计算间隔多少天，则除以毫秒到天的转换公式
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return betweenDate;
    }

    /**
     * 获取当前时间
     *
     * @param
     * @return YYYY-MM-DD
     */
    public static String getCurrentTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Calendar calendar = Calendar.getInstance();
        String time = sdf.format(new Date());
        return time;
    }

    /**
     * 根据日期获取当天是周几
     *
     * @param datetime 日期
     * @return 周几
     */
    public static String dateToWeek(String datetime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
        Calendar cal = Calendar.getInstance();
        Date date;
        try {
            date = sdf.parse(datetime);
            cal.setTime(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        return weekDays[w];
    }

    /**
     * 获取明天的日期字符串
     *
     * @return
     */
    public static String tomorrowDateStr() {
        Date date = new Date();//取时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        //把日期往后增加一天.整数往后推,负数往前移动(1:表示明天、-1：表示昨天，0：表示今天)
        calendar.add(Calendar.DATE, 1);

        //这个时间就是日期往后推一天的结果
        date = calendar.getTime();

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String tomorrowStr = formatter.format(date);
        return tomorrowStr;
    }

    /**
     * 获取当前时间与指定时间的间隔分钟数
     *
     * @param
     * @return YYYY-MM-DD
     */
    public static Long getIntervalMinutes(String orderTime) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long currentTime = System.currentTimeMillis();
        //从对象中拿到时间
        long createTime = 0;
        try {
            createTime = df.parse(orderTime).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long diff = (currentTime - createTime) / 1000 / 60;
        System.out.println("当前系统时间为：" + currentTime + "下单时间为：" + createTime + "两个时间差为：" + diff);
        return diff;
    }

    /**
     * 获取指定时间减去一定的分钟数
     *
     * @param
     * @return YYYY-MM-DD
     */
    public static String reduceIntervalMinutes(String apponitTime, int minutes) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long createTime = 0;
        try {
            createTime = df.parse(apponitTime).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long time = createTime - minutes * 60 * 1000;
        String dateStr = df.format(time);
        return dateStr;
    }

    /**
     * 获取指定时间加上一定的分钟数
     *
     * @param
     * @return YYYY-MM-DD
     */
    public static String addIntervalMinutes(String apponitTime, int minutes) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long createTime = 0;
        try {
            createTime = df.parse(apponitTime).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long time = createTime + minutes * 60 * 1000;
        String dateStr = df.format(time);
        return dateStr;
    }

    /**
     * 获取指定时间的时间戳格式
     *
     * @param
     * @return YYYY-MM-DD
     */
    public static Long getAppointTimeStamp(String apponitTime) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long time = 0;
        try {
            time = df.parse(apponitTime).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time;
    }

    /**
     * 获取RFC3339标准时间格式
     *
     * @param timeStamp
     * @return YYYY-MM-DD
     */
    public static String timeStampToRfc3339(long timeStamp) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        String formatDate = simpleDateFormat.format(new Date(timeStamp));
        return formatDate;
    }

    /**
     * 提供POST请求，跨项目进行查询和提交请求。
     *
     * @param
     * @return 两个参数的积
     */
    public static String doPost(String url, CDO cdoRequest) throws Exception {
        String result = null;
        //设置请求的状态参数
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(6000).setConnectTimeout(6000)
                .setSocketTimeout(6000).build();

        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(requestConfig);
            // 参数不为空
            if (null != cdoRequest) {
                HttpEntity httpEntity = new StringEntity(cdoRequest.toJSONString());
                httpPost.setEntity(httpEntity);
            } else {
                UrlEncodedFormEntity formEntity = null;
                httpPost.setEntity(formEntity);
            }
            CloseableHttpResponse response = httpClient.execute(httpPost);
            try {
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity);
            } finally {
                response.close();
            }
        } finally {
            httpClient.close();
        }
        return result;
    }




    /* 发送 post请求 用HTTPclient 发送请求*/
    public static byte[] sendPost(String URL, String json) {
        String obj = null;
        InputStream inputStream = null;
        Buffer reader = null;
        byte[] data = null;
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httppost = new HttpPost(URL);
        httppost.addHeader("Content-type", "application/json; charset=utf-8");
        httppost.setHeader("Accept", "application/json");
        try {
            StringEntity s = new StringEntity(json, Charset.forName("UTF-8"));
            s.setContentEncoding("UTF-8");
            httppost.setEntity(s);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                // 获取相应实体
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    inputStream = entity.getContent();
                    data = readInputStream(inputStream);
                }
                return data;
            } finally {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return data;
    }

    /**
     * 将流 保存为数据数组
     *
     * @param inStream
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        // 创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        // 每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len = 0;
        // 使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            // 用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        // 关闭输入流
        inStream.close();
        // 把outStream里的数据写入内存
        return outStream.toByteArray();
    }

    /**
     * 字符数组转换为字符串
     *
     * @param bArr
     * @return
     */
    public static String bytesToHexString(byte[] bArr) {
        StringBuffer sb = new StringBuffer(bArr.length);
        String sTmp;

        for (int i = 0; i < bArr.length; i++) {
            sTmp = Integer.toHexString(0xFF & bArr[i]);
            if (sTmp.length() < 2) {
                sb.append(0);
            }
            sb.append(sTmp.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 获取随机字符串UUID
     *
     * @param
     * @return
     */
    public static String getUUID() {
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
        return uuid;
    }

    /**
     * DecimalFormat转换最简便
     */
    public static String doubleSplit(Double f, int n) {
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(n);
        System.out.println(nf.format(f));
        return nf.format(f);
    }

    public static Double getDoubleTwoBit(String doubleStr) {
        Double double0 = Double.parseDouble(doubleStr);//6.2041    这个是转为double类型
        DecimalFormat df = new DecimalFormat("0.00");
        String priceStr = df.format(double0); //6.20   这个是字符串，但已经是我要的两位小数了
        Double price = Double.parseDouble(priceStr); //6.20
        return price;
    }

    public static String parsDate(String date, String formatter, String formatter2) {
        return LocalDateTime.parse(date, DateTimeFormatter.ofPattern(formatter)).format(DateTimeFormatter.ofPattern(formatter2));
    }

    public static String getFirstDayOfMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR, year);
        //设置月份
        cal.set(Calendar.MONTH, month - 1);
        //获取某月最小天数
        int firstDay = cal.getMinimum(Calendar.DATE);
        //设置日历中月份的最小天数
        cal.set(Calendar.DAY_OF_MONTH, firstDay);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(cal.getTime());
    }

    public static String getWeekFirstDay() {
        Date today = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(today);
        int weekday = c.get(Calendar.DAY_OF_WEEK);
        //周日
        if (weekday == 1) {
            weekday = 8;
        }
        String dateByDay = Utils.getDateByDay(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")), 2 - weekday);
        return dateByDay;
    }

    public static String getWeekLastDay() {
        Date today = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(today);
        int weekday = c.get(Calendar.DAY_OF_WEEK);
        //周日
        if (weekday == 1) {
            weekday = 8;
        }
        String dateByDay = Utils.getDateByDay(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")), 8 - weekday);
        return dateByDay;
    }

    public static int getWeekOfYear() {
        Date today = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(today);
        int week = c.get(Calendar.WEEK_OF_YEAR);
        return week;
    }

    /**
     * 获取当天星期几
     *
     * @return
     */
    public static int getWeekDay() {
        Date today = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(today);
        int weekday = c.get(Calendar.DAY_OF_WEEK);
        weekday = weekday - 1;
        if (weekday == 0) {
            weekday = 7;
        }
        return weekday;
    }

    public static int getWeekDay(String beforeDate) {
        DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = format2.parse(beforeDate);
            Calendar c = Calendar.getInstance();
            c.setTime(date);
            int weekday = c.get(Calendar.DAY_OF_WEEK);
            weekday = weekday - 1;
            if (weekday == 0) {
                weekday = 7;
            }
            return weekday;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 获取当天星期几
     *
     * @return
     */
    public static String getWeekDayValue() {
        String week = "";
        Date today = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(today);
        int weekday = c.get(Calendar.DAY_OF_WEEK);
        if (weekday == 1) {
            week = "周日";
        } else if (weekday == 2) {
            week = "周一";
        } else if (weekday == 3) {
            week = "周二";
        } else if (weekday == 4) {
            week = "周三";
        } else if (weekday == 5) {
            week = "周四";
        } else if (weekday == 6) {
            week = "周五";
        } else if (weekday == 7) {
            week = "周六";
        }
        return week;
    }

    public static String getMonthLastDay(int year, int month) {
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR, year);
        //设置月份
        cal.set(Calendar.MONTH, month - 1);
        //获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DATE);
        //设置日历中月份的最大天数
        cal.set(Calendar.DAY_OF_MONTH, lastDay);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(cal.getTime());
    }

    public static String getDate(String beforeDate, int interval, int field) {
        DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        if (!"now".equals(date)) {
            try {
                date = format2.parse(beforeDate);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        c.add(field, interval);
        String time = format.format(c.getTime());

        return time;
    }

    public static String getDateByDay(String beforeDate, int interval) {
        return getDate(beforeDate, interval, Calendar.DATE);
    }

    public static String getDateByMonth(String beforeDate, int interval) {
        return getDate(beforeDate, interval, Calendar.MONTH);
    }

    public static String getDateByYear(String beforeDate, int interval) {
        return getDate(beforeDate, interval, Calendar.YEAR);
    }

    public static String getDateToday() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }

    public static String getDateYestoday() {
        return getDate(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")), -1, Calendar.DATE);
    }

    public static String getDateTomorrow() {
        return getDate(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")), 1, Calendar.DATE);
    }

    public static String getChineseValueOfGoodsName(String value) {
        if (value.matches("[\u4E00-\u9FA5]+")) {
            //全中文
        } else {
            //非中文
            int nameLength = value.length();
            StringBuffer nameBuf = new StringBuffer();
            for (int i = 0; i < nameLength; i++) {
                String substring = value.substring(i, i + 1);
                if (substring.matches("[\u4E00-\u9FA5]+")) {
                    //全中文
                    nameBuf.append(substring);
                }
            }
            value = nameBuf.toString()
                    .replaceAll("精品", "")
                    .replaceAll("折价", "")
                    .replaceAll("特价", "")
                    .replaceAll("高级", "")
                    .replaceAll("kg", "")
//                    .replaceAll("（", "")
//                    .replaceAll("）", "")
//                    .replaceAll("\\(", "")
//                    .replaceAll("\\)", "")
            ;
        }
        return value;
    }

//    public static String getChineseValue(String value) {
//        if (value.matches("[\u4E00-\u9FA5]+")) {
//            //全中文
//        } else {
//            //非中文
//            int nameLength = value.length();
//            StringBuffer nameBuf = new StringBuffer();
//            for (int i = 0; i < nameLength; i++) {
//                String substring = value.substring(i, i + 1);
//                if (substring.matches("[\u4E00-\u9FA5]+")) {
//                    //全中文
//                    nameBuf.append(substring);
//                }
//            }
//            value = nameBuf.toString().replaceAll("特价", "");
//        }
//        return value;
//    }

    /**
     * 汉字：[0x4e00,0x9fa5]（或十进制[19968,40869]）
     * 数字：[0x30,0x39]（或十进制[48, 57]）
     * 小写字母：[0x61,0x7a]（或十进制[97, 122]）
     * 大写字母：[0x41,0x5a]（或十进制[65, 90]）
     * 其他：除上所有
     */
    @Deprecated
    public static String getPinYinOfPinYin4j(String chinese) {
        StringBuilder sb = new StringBuilder();
        char[] arr = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE); // 转大写
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); // 不加音调
        for (char c : arr) {
            if (c >= 0x4E00 && c <= 0x9FA5) { // 中文判断
                try {
                    sb.append(PinyinHelper.toHanyuPinyinStringArray(c, defaultFormat)[0]);
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else if (c >= 0x61 && c <= 0x7a || c >= 0x41 && c <= 0x5a) {
                sb.append(c);
            }
        }
        return sb.toString().toUpperCase();
    }


    /**
     * 判断字符串是否为数字
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    public static int getInt0T10() {
        Random r = new Random();
        return r.nextInt(10);
//        int n3 = Math.abs(r.nextInt() % 10);
//        System.out.println("n2:"+n2);
//        System.out.println("n3:"+n3);
    }

    public static String getInt10T99() {
        Random random = new Random();
        int ends = random.nextInt(99);
        return String.format("%02d", ends);
    }

    public static long getDiscountChangeFee(long actualFee, boolean enable) {
        if (!enable) {
            return 0;
        }
        long discountChangeFee = 0;
        if (actualFee % 10 >= 5) {
            discountChangeFee = 10 - actualFee % 10;
        } else {
            discountChangeFee = 0 - actualFee % 10;
        }
        return discountChangeFee;
    }

    public static long getChangeFee(long realFee, long actualFee) {
        long changeFee = 0;
        if (actualFee % 10 >= 5) {
            changeFee = realFee - (actualFee - actualFee % 10 + 10);
        } else {
            changeFee = realFee - (actualFee - actualFee % 10);
        }
        log.error("aaaaa{},{},{}", realFee, actualFee, changeFee);
        return changeFee;
    }

    /**
     * 四舍五入
     *
     * @return
     */
    public static double getValueRounded(double value) {
        long lValue = Double.valueOf(multiply(value, 100.0, 0)).longValue();
        if (lValue % 10 >= 5) {
            lValue = lValue - lValue % 10 + 10;
        } else {
            lValue = lValue - lValue % 10;
        }
        return Double.valueOf(multiply(lValue, 0.01, 2));
    }

    public static long getValueRounded(long lValue) {
        if (lValue % 10 >= 5) {
            lValue = lValue - lValue % 10 + 10;
        } else {
            lValue = lValue - lValue % 10;
        }
        return lValue;
    }

    public static String getFormatValueOfSpaceByRight(String value, int length) {
        if(length<=0){
            return value;
        }
        return String.format("%1$-" + length + "s", value);
    }

    public static String getFormatValueOfSpaceByLeft(String value, int length) {
        if(length<=0){
            return value;
        }
        return String.format("%" + length + "s", value);
    }
    public static String getSpace(int length) {
        if(length<=0){
            return "";
        }
        length=length+1;
        return String.format("%" + length + "s", "a").replaceAll("a"," ");
    }

    public static String getFormatValueOfZero(int value, int length) {
        return String.format(String.format("%0" + length + "d", value));
    }


    public static String getValueByFillZero(String value, int count) {
        if (StringUtils.isNotBlank(value) && value.length() != count) {
            int iValue = Integer.parseInt(value);
            value = String.format("%0" + count + "d", iValue);
        }
        return value;
    }
    /**
     * 获取整数的负数
     *
     * @param a
     * @return
     */
    public static int getNegativeInt(int a) {
        return ~(a - 1);
    }



    public static String getBarcode(double weight, double price, int code, String weigherBarcodeRule, int weigherPriceRule, int weigherPricePrecision) {
        String barcode = "";
        if (weight > 0) {
            int pricePrecision = weigherPricePrecision; //称重价格精度： 0 角；1 分
            int priceRule = weigherPriceRule; //称重商品抹零规则：0 默认实际价格； 1 全入； 2 四舍五入； 3 全舍
            //重量转换为克：g
            int weightInt = (int) (weight * 1000);
            //总价，单位分
            int amount = (int) (price * 100 * weight);
            //根据商户配置的称重抹零规则进行金额调整
            if (pricePrecision == 0) {
                String amountStr = String.valueOf(amount);
                int remainder = Integer.parseInt(amountStr.substring(amountStr.length() - 1));
                switch (priceRule) {
                    case 0:
                        break;
                    case 1:
                        if (remainder > 0) {
                            amount = (amount / 10 + 1) * 10;
                        }
                        break;
                    case 2:
                        if (remainder > 4) {
                            amount = (amount / 10 + 1) * 10;
                        } else {
                            amount = amount / 10 * 10;
                        }
                        break;
                    case 3:
                        if (remainder > 0) {
                            amount = amount / 10 * 10;
                        }
                    default:
                }
            }

            if (weigherBarcodeRule.length() == 18) {
                String prefix = weigherBarcodeRule.substring(0, 2);
                String step1 = weigherBarcodeRule.substring(2, 7);
                String step2 = weigherBarcodeRule.substring(7, 12);
                String step3 = weigherBarcodeRule.substring(12, 17);
                String step1code = "";
                String step2code = "";
                String step3code = "";
                switch (step1) {
                    case "AAAAA":
                        step1code = String.format("%05d", code);
                        break;
                    case "BBBBB":
                        step1code = String.format("%05d", weightInt);
                        break;
                    case "CCCCC":
                        step1code = String.format("%05d", amount);
                        break;
                }
                switch (step2) {
                    case "AAAAA":
                        step2code = String.format("%05d", code);
                        break;
                    case "BBBBB":
                        step2code = String.format("%05d", weightInt);
                        break;
                    case "CCCCC":
                        step2code = String.format("%05d", amount);
                        break;
                }
                switch (step3) {
                    case "AAAAA":
                        step3code = String.format("%05d", code);
                        break;
                    case "BBBBB":
                        step3code = String.format("%05d", weightInt);
                        break;
                    case "CCCCC":
                        step3code = String.format("%05d", amount);
                        break;
                }
                barcode = prefix + step1code + step2code + step3code + new Random().nextInt(10);
            } else {
                String prxfix = weigherBarcodeRule.substring(0, 2);
                barcode = prxfix + String.format("%05d", code) + String.format("%05d", amount) + new Random().nextInt(10);
            }
            //称重商品，重新拼接条码: 2位开头+5位条码+5位金额+5位重量+1校验位
        }

        return barcode;
    }

    public static String getAuthCode() {
        String dateToday = getDateToday();
        int weekDay = getWeekDay(dateToday);
        String a = dateToday.replace("-", "");
        a = a.substring(2, 8);
        String abc = (Integer.parseInt(a) * weekDay * Integer.parseInt(a.substring(4, 6))) + "";
        return abc;
    }
}
